package com.worldwind.test;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.FrameLayout;

import com.R;

import java.util.Iterator;
import java.util.Locale;

import gov.nasa.worldwind.FrameMetrics;
import gov.nasa.worldwind.WorldWindow;
import gov.nasa.worldwind.globe.BasicElevationCoverage;
import gov.nasa.worldwind.layer.BackgroundLayer;
import gov.nasa.worldwind.layer.BlueMarbleLandsatLayer;
import gov.nasa.worldwind.layer.Layer;
import gov.nasa.worldwind.layer.LayerList;
import gov.nasa.worldwind.layer.TiandituCia_cLayer;
import gov.nasa.worldwind.layer.TiandituCva_cLayer;
import gov.nasa.worldwind.layer.TiandituImg_cLayer;
import gov.nasa.worldwind.layer.TiandituVec_cLayer;
import gov.nasa.worldwind.util.Logger;

/**
 * Created by Lenovo on 2018/4/26.
 */

public class LayerNavigatorActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {


    protected static final int PRINT_METRICS = 1;

    protected static final int PRINT_METRICS_DELAY = 3000;

    protected String aboutBoxTitle = "World Wind Cumpus";        // TODO: use a string resource, e.g., app name

    protected String aboutBoxText = "A controller of layers";    // TODO: make this a string resource

    protected static int selectedItemId ;

    protected ActionBarDrawerToggle drawerToggle;

    protected NavigationView navigationView;


    /**
     * The WorldWindow (GLSurfaceView) maintained by this activity
     */
    protected WorldWindow wwd;

/*
    protected Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == PRINT_METRICS) {
                return printMetrics();
            } else {
                return false;
            }
        }
    });
*/

    /**
     * Returns a reference to the WorldWindow.
     * <p>
     * Derived classes must implement this method.
     *
     * @return The WorldWindow GLSurfaceView object
     */
    public WorldWindow getWorldWindow() {
        // TODO: Implement via Fragment Manager and findFragmentById
        return this.wwd;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layer_nav);
        // Create the World Window (a GLSurfaceView) which displays the globe.
        this.wwd = new WorldWindow(this);
        // Override the World Window's built-in navigatior behavior by adding picking support.
        this.wwd.setWorldWindowController(new PickObjectController(this));
        // Add the WorldWindow view object to the layout that was reserved for the globe.
        FrameLayout globeLayout = (FrameLayout) findViewById(R.id.globe);
        globeLayout.addView(this.wwd);

        // Setup the World Window's layers.
        this.wwd.getLayers().addLayer(new BackgroundLayer());
        this.wwd.getLayers().addLayer(new BlueMarbleLandsatLayer());
        // Setup the World Window's elevation coverages.
        this.wwd.getGlobe().getElevationModel().addCoverage(new BasicElevationCoverage());
        //add NavView
        onCreateDrawer();
    }

    @Override
    protected void onResume() {
        super.onResume();
        this.navigationView.setCheckedItem(selectedItemId);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    protected void onCreateDrawer() {
        // Add support for a Toolbar and set to act as the ActionBar
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        /*此处抛出该异常： if (ab instanceof WindowDecorActionBar) {
        throw new IllegalStateException("This Activity already has an action bar supplied " +
                "by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set " +
                 "windowActionBar to false in your theme to use a Toolbar instead.");
        }*/
        //解决方案：设置toolbar的theme,添加style theme资源
        // android:theme="@style/AppTheme.PopupOverlay"
        //关键在于设置Manifest.xml中，设置activity的theme>>android:theme="@style/AppTheme.NoActionBar">
        setSupportActionBar(toolbar);

        // Add support for the navigation drawer full of examples
        //The DrawerLayout to link to the given Activity's ActionBar
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

        this.drawerToggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(this.drawerToggle);
        this.drawerToggle.syncState();
        //添加导航栏监听
        this.navigationView = (NavigationView) findViewById(R.id.nav_view);
        this.navigationView.setNavigationItemSelectedListener(this);
        this.navigationView.setCheckedItem(selectedItemId);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //选项菜单
        getMenuInflater().inflate(R.menu.about_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //如果点击了选项菜单，将显示相应的选项信息
        int id = item.getItemId();
        if (id == R.id.action_about) {
            showAboutBox();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        // Persist the selected item between Activities
        selectedItemId = item.getItemId();

        // Handle navigation view item clicks here.
        switch (selectedItemId) {
            case R.id.TiandituVecLayer:
                //需要允许网络访问，设置manifest中的网络权限，否则无法加载在线服务
                loadLayer(new TiandituVec_cLayer(),R.string.tiandituVecLayerName);
                break;
            case R.id.TiandituImgLayer:
                loadLayer(new TiandituImg_cLayer(), R.string.tiandituImgLayerName);
                break;
            case R.id.TiandituCvaLayer:
                loadLayer(new TiandituCva_cLayer(), R.string.tiandituCvaLayerName);
                break;
            case R.id.TiandituCiaLayer:
                loadLayer(new TiandituCia_cLayer(), R.string.tiandituCiaLayerName);
                break;

        }
        //自动隐藏
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    /**
     * This method is invoked when the About button is selected in the Options menu.
     */
    protected void showAboutBox() {
        //选项菜单被点击后，显示简单信息提示对话框
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setTitle(this.aboutBoxTitle);
        alertDialogBuilder
                .setMessage(this.aboutBoxText)
                .setCancelable(true)
                .setNegativeButton("Close", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // if this button is clicked, just close
                        // the dialog box and do nothing
                        dialog.cancel();
                    }
                });

        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }


   public void  loadLayer(Layer layer,int layerName){
       this.setTitle(layerName);
       layer.setDisplayName(getText(layerName).toString());
       //根据图层名删除已经加载的图层，避免重复加载,
       LayerList layerList = this.wwd.getLayers();
       Iterator<Layer> iterator = layerList.iterator();
       Layer previousLayer = null;
       while (iterator.hasNext()){
           Layer currentlayer = iterator.next();
          if(currentlayer.getDisplayName().equals(getText(layerName).toString())){
              previousLayer = currentlayer;
          }
       }
       //如果图层已存在，删除后加载到当前顶层
       if(previousLayer!=null) {
           this.wwd.getLayers().removeLayer(previousLayer);
       }
       //加载图层
       this.wwd.getLayers().addLayer(layer);
       //重绘
       this.wwd.requestRedraw();

   }

}
